package com.lanou3g.dllo.baidumusic.main;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.lanou3g.dllo.baidumusic.R;
import com.lanou3g.dllo.baidumusic.base.BaseActivity;
import com.lanou3g.dllo.baidumusic.database.SingleLiteOrm;
import com.lanou3g.dllo.baidumusic.main.playerdetail.PlayDetailBean;
import com.lanou3g.dllo.baidumusic.event.IndexEvent;
import com.lanou3g.dllo.baidumusic.main.playmusic.PlayMusicService;
import com.lanou3g.dllo.baidumusic.main.playerdetail.PlayerDetailActivity;
import com.lanou3g.dllo.baidumusic.main.playmusic.PlayOrPause;
import com.lanou3g.dllo.baidumusic.main.playmusic.PlaymusicBean;
import com.lanou3g.dllo.baidumusic.main.playmusic.PopAdapter;
import com.lanou3g.dllo.baidumusic.event.SongIdEvent;
import com.lanou3g.dllo.baidumusic.main.playmusic.SongPlayBean;
import com.lanou3g.dllo.baidumusic.mine.localmusic.LocalMusicFragment;
import com.lanou3g.dllo.baidumusic.mine.myfavorite.MyFavoriteFragment;
import com.lanou3g.dllo.baidumusic.mine.recentlyplay.RecentlyPlayFragment;
import com.lanou3g.dllo.baidumusic.musiclibrary.playlist.playlistdetail.PlaylistDetailFragment;
import com.lanou3g.dllo.baidumusic.musiclibrary.ranklist.ranklistdetail.RanklistDetailFragment;
import com.lanou3g.dllo.baidumusic.musiclibrary.recommend.allsinger.AllSingerFragment;
import com.lanou3g.dllo.baidumusic.musiclibrary.recommend.allsingerdetail.AllSingerDetailFragment;
import com.lanou3g.dllo.baidumusic.musiclibrary.recommend.singersdetail.SingersDetailFragment;
import com.lanou3g.dllo.baidumusic.search.SearchFragment;
import com.lanou3g.dllo.baidumusic.tools.OnRemoveListener;
import com.lanou3g.dllo.baidumusic.tools.PlaylistManager;
import com.lanou3g.dllo.baidumusic.tools.SingleVolley;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
;
import java.util.Random;
import java.util.Stack;


public class MainActivity extends BaseActivity implements View.OnClickListener {

    private FrameLayout mainFrameLayout;
    private MainFragment mainFragment = new MainFragment();
    private static FragmentManager fm;
    private static FragmentTransaction tran;
    private RanklistDetailFragment ranklistDetailFragment = new RanklistDetailFragment();
    private PlaylistDetailFragment playlistDetailFragment = new PlaylistDetailFragment();
    private MyFavoriteFragment myFavoriteFragment = new MyFavoriteFragment();
    private ImageView mainPlayerPhoto;
    private TextView mainMusicplayerMusicSongName, mainMusicPlayersinger;
    private ServiceConnection serviceConnection;
    private PlayMusicService.MyBinder myBinder;
    private AllSingerFragment allSingerFragment = new AllSingerFragment();
    private AllSingerDetailFragment allSingerDetailFragment = new AllSingerDetailFragment();
    private SingersDetailFragment singersDetailFragment = new SingersDetailFragment();
    private RecentlyPlayFragment recentlyPlayFragment = new RecentlyPlayFragment();
    private LocalMusicFragment localMusicFragment = new LocalMusicFragment();
    private SearchFragment searchFragment = new SearchFragment();
    private Stack<Fragment> fragmentStack;// fragment栈
    private PopupWindow popupWindow;
    private PopAdapter popAdapter;
    private int pattern = 0;
    private CheckBox playerPlayBtn;
    private RelativeLayout mainMusicplayLayout;
    private PlayDetailBean playDetailBean;
    long exitTime = 0;
    private SongPlayBean songPlayBean;

    @Override
    public int setLayout() {
        EventBus.getDefault().register(this);
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        mainMusicplayLayout = (RelativeLayout) findViewById(R.id.main_musicplay_layout);
        mainMusicplayLayout.setOnClickListener(this);
        playerPlayBtn = (CheckBox) findViewById(R.id.main_player_play);
        playerPlayBtn.setChecked(PlaylistManager.getInstance().isPlaying);
        // 暂停播放按钮
        playerPlayBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                playerPlayBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharedPreferences sharedPreferences = getSharedPreferences("playerInfo", MODE_PRIVATE);
                        String songId = sharedPreferences.getString("songId",null);
                        if (PlaylistManager.getInstance().getPlaylist().size() == 0) {
                            Toast.makeText(MainActivity.this, "当前没有可播放歌曲", Toast.LENGTH_SHORT).show();
                        } else if(songId != null){
                            EventBus.getDefault().post(new SongIdEvent(songId));
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("songId",null);
                            editor.commit();
                        } else {
                            myBinder.playPause();
                        }
                    }
                });
            }
        });

        findViewById(R.id.main_player_menu_btn).setOnClickListener(this);
        findViewById(R.id.main_player_nextsong).setOnClickListener(this);
        mainFrameLayout = (FrameLayout) findViewById(R.id.main_framelayout);
        mainPlayerPhoto = (ImageView) findViewById(R.id.main_playerphoto);
        mainMusicplayerMusicSongName = (TextView) findViewById(R.id.main_musicplayer_musicsongname);
        mainMusicPlayersinger = (TextView) findViewById(R.id.main_musicplayer_singer);
    }

    @Override
    public void initData() {
        playerInfo();
        fragmentStack = new Stack<>();
        fm = getSupportFragmentManager();
        tran = fm.beginTransaction();
        fragmentStack.push(mainFragment);
        tran.replace(R.id.main_framelayout, mainFragment, "MainFragment").commit();

        // 绑定服务
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myBinder = (PlayMusicService.MyBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        Intent playMusicService = new Intent(this, PlayMusicService.class);
        startService(playMusicService);
        bindService(playMusicService, serviceConnection, BIND_AUTO_CREATE);
    }

    // 隐藏当前界面,跳转到RanklistDetailFragment界面
    public void toRanklistDetail(int rankType) {
        fragmentStack.push(ranklistDetailFragment);
        fm.beginTransaction().add(R.id.main_framelayout, ranklistDetailFragment, "RanklistDetailFragment").commit();
        fm.beginTransaction().hide(mainFragment).commit();
        Bundle bundle = new Bundle();
        bundle.putInt("rankType", rankType);
        ranklistDetailFragment.setArguments(bundle);
    }

    // 隐藏当前界面,跳转到PlaylistDetailFragment界面
    public void toPlaylistDetail(String listid) {
        fragmentStack.push(playlistDetailFragment);
        fm.beginTransaction().add(R.id.main_framelayout, playlistDetailFragment, "PlaylistDetailFragment").commit();
        fm.beginTransaction().hide(mainFragment).commit();
        Bundle bundle = new Bundle();
        bundle.putString("listid", listid);
        playlistDetailFragment.setArguments(bundle);
    }

    // 全部歌手二级界面
    public void toAllSinger() {
        fragmentStack.push(allSingerFragment);
        fm.beginTransaction().add(R.id.main_framelayout, allSingerFragment, "AllSingerFragment")
                .hide(mainFragment).commit();
    }

    // 全部歌手三级界面
    public void toAllSingerDetail(String url, String type) {
        Fragment current = fragmentStack.pop();
        fragmentStack.push(current);
        fragmentStack.push(allSingerDetailFragment);
        fm.beginTransaction().add(R.id.main_framelayout, allSingerDetailFragment, "AllSingerDetailFragment")
                .hide(current).commit();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        bundle.putString("type", type);
        allSingerDetailFragment.setArguments(bundle);
    }

    // 全部歌手四级界面
    public void toSingerDetail(String url, String tingUid, String pictureUrl) {
        Fragment current = fragmentStack.pop();
        fragmentStack.push(current);
        fragmentStack.push(singersDetailFragment);
        fm.beginTransaction().add(R.id.main_framelayout, singersDetailFragment, "SingersDetailFragment")
                .hide(current).commit();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        bundle.putString("artistId", tingUid);
        bundle.putString("pictureUrl", pictureUrl);
        singersDetailFragment.setArguments(bundle);
    }

    // 返回键调用的方法
    public void finishNew() {
        if (fragmentStack.size() > 1) {
            // pop():移除当前栈顶元素
            Fragment current = fragmentStack.pop();
            Fragment preFragment = fragmentStack.pop();
            getSupportFragmentManager().beginTransaction().remove(current)
                    .show(preFragment).commit();
            fragmentStack.push(preFragment);
        }
    }

    // 主页搜索按钮跳转到搜索界面方法
    public void toSearch() {
        fragmentStack.push(searchFragment);
        fm.beginTransaction().add(R.id.main_framelayout, searchFragment, "SearchFragment")
                .hide(mainFragment).commit();
    }

    // 我的最近播放跳转到详情界面
    public void toRecentlyPlayDetail() {
        fragmentStack.push(recentlyPlayFragment);
        fm.beginTransaction().add(R.id.main_framelayout, recentlyPlayFragment, "RecentlyPlayFragment")
                .hide(mainFragment).commit();
    }

    // 我的我喜欢的单曲跳转到详情界面的方法
    public void toMyFavoriteDetail() {
        fragmentStack.push(myFavoriteFragment);
        fm.beginTransaction().add(R.id.main_framelayout, myFavoriteFragment, "MyFavoriteFragment")
                .hide(mainFragment).commit();
    }

    // 我的界面本地音乐跳转到详情界面
    public void toLocalMusicDetail() {
        fragmentStack.push(localMusicFragment);
        fm.beginTransaction().add(R.id.main_framelayout, localMusicFragment, "LocalMusicFragment")
                .hide(mainFragment).commit();
    }

    // 要关闭的时候设置下面播放器的歌曲的头像,歌名,歌手,songId,然后在onCreate中调用一下;
    public void playerInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences("playerInfo", MODE_PRIVATE);
        String title = sharedPreferences.getString("title", "百度音乐  听到极致");
        String author = sharedPreferences.getString("author", "");
        String songId = sharedPreferences.getString("songId", "");
        String photo = sharedPreferences.getString("photo", "");

        mainMusicplayerMusicSongName.setText(title);
        mainMusicPlayersinger.setText(author);
        SingleVolley.getSingleVolley(this).getImageLoader().get(photo,
                ImageLoader.getImageListener(mainPlayerPhoto, R.mipmap.view_loading, R.mipmap.view_loading));
    }

    // 获取最后播放信息,最后在onDestroy中调用
    public void lastestSongInfo() {
        if (songPlayBean != null) {
            SharedPreferences sp = getSharedPreferences("playerInfo", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("title", songPlayBean.getSonginfo().getTitle());
            editor.putString("author", songPlayBean.getSonginfo().getAuthor());
            editor.putString("photo", songPlayBean.getSonginfo().getPic_big());
            editor.putString("songId", songPlayBean.getSonginfo().getSong_id());
            editor.commit();
        }
    }

    // 获得服务传过来的点击的歌曲的头像,歌名,歌手
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getSongsInfo(SongPlayBean songPlayBean) {
        this.songPlayBean = songPlayBean;
        SingleVolley.getSingleVolley(this).getImageLoader().get(songPlayBean.getSonginfo().getPic_big(),
                ImageLoader.getImageListener(mainPlayerPhoto, R.mipmap.view_loading, R.mipmap.view_loading));
        mainMusicplayerMusicSongName.setText(songPlayBean.getSonginfo().getTitle());
        mainMusicPlayersinger.setText(songPlayBean.getSonginfo().getAuthor());

        playDetailBean = new PlayDetailBean(songPlayBean.getSonginfo().getTitle(), songPlayBean.getSonginfo()
                .getAuthor(), songPlayBean.getSonginfo().getPic_premium(), songPlayBean.getSonginfo().getLrclink());
    }

    // 接收服务里发出的PlayOrPause
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void controlPlayOrPause(PlayOrPause playOrPause) {
        playerPlayBtn.setChecked(playOrPause.isPlaying());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 显示播放列表
            case R.id.main_player_menu_btn:
                if (popupWindow == null || !popupWindow.isShowing()) {
                    showPlayList();
                } else {
                    popupWindow.dismiss();
                }
                break;
            // 下一曲
            case R.id.main_player_nextsong:
                if (PlaylistManager.getInstance().getPlaylist().size() == 0) {
                    myBinder.playStop();
                } else {
                    myBinder.playNext(pattern);
                }
                break;
            // 歌曲详情界面(照片,歌词)
            case R.id.main_musicplay_layout:
                // 把打包的实体类和播放模式传过去
                Intent intent = new Intent(this, PlayerDetailActivity.class);
                intent.putExtra("playDetailBean", playDetailBean);
                intent.putExtra("pattern", myBinder.getPattern());
                startActivity(intent);
                if (popupWindow == null) {
                    return;
                } else {
                    popupWindow.dismiss();
                }
                break;
        }
    }

    // 显示播放列表
    private void showPlayList() {

        popAdapter = new PopAdapter(this);

        // 获取屏幕高度
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        display.getMetrics(displayMetrics);

        // 绑定布局
        View view = LayoutInflater.from(this).inflate(R.layout.popwindow_alert, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT
                , displayMetrics.heightPixels / 4 * 3);
        popupWindow.showAsDropDown(mainFrameLayout, 0, -displayMetrics.heightPixels / 4 * 3);

        final ImageView playPattern = (ImageView) view.findViewById(R.id.playmusic_popwindow_model);
        TextView popPlayinglist = (TextView) view.findViewById(R.id.playmusic_popwindow_playinglist);
        TextView popClearAll = (TextView) view.findViewById(R.id.playmusic_popwindow_clearall);
        ListView popListView = (ListView) view.findViewById(R.id.playmusic_popwindow_listview);

        popAdapter.setDatas(PlaylistManager.getInstance().getPlaylist());
        popListView.setAdapter(popAdapter);

        // 点击播放
        popListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 发送EventBus给服务
                EventBus.getDefault().post(new SongIdEvent(PlaylistManager.getInstance().getPlaylist().get(position).getSongId()));
                EventBus.getDefault().post(new IndexEvent(position));
            }
        });

        // 点击删除
        popAdapter.setOnRemoveListener(new OnRemoveListener() {
            @Override
            public void onRemoveClick(int position) {
                PlaylistManager.getInstance().getPlaylist().remove(position);
                popAdapter.setDatas(PlaylistManager.getInstance().getPlaylist());
                // 播放的位置
                if (myBinder.playingPosition(position)) {
                    if (myBinder.getPattern() == 1) {
                        EventBus.getDefault().post(new IndexEvent(position));
                    } else if (myBinder.getPattern() == 2) {
                        Random random = new Random();
                        int pos = random.nextInt(PlaylistManager.getInstance().getPlaylist().size());
                        EventBus.getDefault().post(new IndexEvent(pos));
                    } else {
                        EventBus.getDefault().post(new IndexEvent(position - 1));
                    }
                    myBinder.playNext(pattern);
                }
            }
        });

        // 初始化播放模式图标
        switch (myBinder.getPattern()) {
            case 0:
                playPattern.setImageResource(R.mipmap.liebiao);
                break;
            case 1:
                playPattern.setImageResource(R.mipmap.danqu);
                break;
            case 2:
                playPattern.setImageResource(R.mipmap.suiji);
                break;
            case 3:
                playPattern.setImageResource(R.mipmap.shunxu);
                break;
        }

        // 设置播放模式
        playPattern.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pattern++;
                if (pattern > 3) {
                    pattern = 0;
                }
                // 设置播放模式
                myBinder.setPattern(pattern);
                switch (pattern) {
                    case 0:
                        playPattern.setImageResource(R.mipmap.liebiao);
                        Toast.makeText(MainActivity.this, "列表循环", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        playPattern.setImageResource(R.mipmap.danqu);
                        Toast.makeText(MainActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        playPattern.setImageResource(R.mipmap.suiji);
                        Toast.makeText(MainActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        playPattern.setImageResource(R.mipmap.shunxu);
                        Toast.makeText(MainActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });

        // 点击播放列表关闭popwindow
        popPlayinglist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        // 全部清除方法
        popClearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlaylistManager.getInstance().getPlaylist().clear();
                popAdapter.setDatas(PlaylistManager.getInstance().getPlaylist());
                myBinder.playStop();
            }
        });

    }

    // 点击返回键两次退出方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 手机上按返回键退出的方法
        if (fragmentStack.size() > 1) {
            finishNew();
            // 消费掉这次点击事件
            return true;
        } else {
            if (keyCode == event.KEYCODE_BACK) {
                //System.currentTimeMillis() 返回一个当前系统时间的毫秒数(long)
                //判断按下返回键的时间与上一次的时间差,也就是说如果连续点击两次的时间在2秒之外
                if (System.currentTimeMillis() - exitTime > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    //将系统时间赋值给exitTime
                    exitTime = System.currentTimeMillis();
                }

                //否则退出
                else {
                    finish();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        SingleLiteOrm.getSingleLiteOrm().getLiteOrm().deleteAll(PlaymusicBean.class);
        SingleLiteOrm.getSingleLiteOrm().getLiteOrm().insert(PlaylistManager.getInstance().getPlaylist());
        unbindService(serviceConnection);
        lastestSongInfo();
        super.onDestroy();
    }
}
